package com.toobulkeh.compuprov.scene;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import org.apache.commons.io.FileUtils;

import com.toobulkeh.search.ImageSearch;
import com.toobulkeh.search.ImageSearchResult;

public class ScenePicker extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5480111163019903758L;
	private static final String OUTPUT_BG_DIR = "C:\\output\\bgs";
	private Container cp;
	private ButtonListener butHandler;
	private ImageListener imgHandler;
	private static final int NUM_SEARCHES = 3;
	private ImageSearchResult result;
	private static final int WINDOW_WIDTH = 1024;
	private static final int WINDOW_HEIGHT = 768;
	private static final Dimension WINDOW_SIZE = new Dimension(WINDOW_WIDTH,WINDOW_HEIGHT);
	private int saveIndex;
	private JLabel chosenScene;
	private ImageSearch gSearch;
	
	public ScenePicker() {
		this.setPreferredSize(WINDOW_SIZE);
		saveIndex = 0;
		butHandler = new ButtonListener();
		imgHandler = new ImageListener();
		cp = this.getContentPane();
		mainPanel();
	}
	
	public void mainPanel() {
		cp.removeAll();
		JPanel bgP = new JPanel(new BorderLayout());
		JPanel bgCP = new JPanel();
		FunnyJTextField searchTF = new FunnyJTextField("Type here to search...",20); //new JTextField("Type here to search...");
		JLabel searchLabel = new JLabel("Enter a word/phrase to search for a scene!",
		                    JLabel.CENTER);
		searchLabel.setFont(new Font("SansSerif", Font.BOLD, 34));
		searchLabel.setVerticalTextPosition(JLabel.CENTER);
		searchLabel.setHorizontalTextPosition(JLabel.CENTER);
		searchTF.setActionCommand("searchTF");
		searchTF.addActionListener(butHandler);
		searchTF.setHorizontalAlignment(JTextField.CENTER);
		
		bgCP.add(searchTF);
		bgP.add(searchLabel, BorderLayout.NORTH);
		bgP.add(bgCP, BorderLayout.CENTER);
		
		bgP.setPreferredSize(WINDOW_SIZE);
		cp.add(bgP);
		this.pack();
	}
	
	public void thanksDialog(JLabel imgThumb) {
		mainPanel();
		JOptionPane.showMessageDialog(this, "Nice Scene!", "Scene Chosen", JOptionPane.PLAIN_MESSAGE, chosenScene.getIcon());
	}
	
	public void imgPanel() {
		cp.removeAll();
		JPanel imgP = new JPanel(new BorderLayout());
		JButton startOver = new JButton("New Search");
		startOver.addActionListener(butHandler);
		startOver.setActionCommand("restart");
		JPanel imgsP = new JPanel(new GridLayout(0,6));
		new GridLayout();
		
		ImageIcon tmpImg;
		JLabel tmpLabel;
		
		//System.out.println("Got BG results... Total: "+result.getSize());
		
		JScrollPane imgsSP = new JScrollPane(imgsP);
		imgP.add(startOver, BorderLayout.NORTH);
		imgP.setPreferredSize(WINDOW_SIZE);
		imgP.add(imgsSP, BorderLayout.CENTER);
		cp.add(imgP);

		
		for(int numSearches = 0; numSearches < NUM_SEARCHES; numSearches++) {
			result = gSearch.search(result);
		}
		for(int i = 0; i < result.getSize(); i++) {
			tmpImg = result.getNextImage().getThumbIcon();
			tmpLabel = new JLabel(tmpImg);
			tmpLabel.setBorder(BorderFactory.createLineBorder(Color.black));
			tmpLabel.setName("bg"+i);
			tmpLabel.addMouseListener(imgHandler);
			imgsP.add(tmpLabel);
			this.pack();
		}
		if(result.getSize() == 0) {
			mainPanel();
			JOptionPane.showMessageDialog(this, "No Images Found!", "Error!", JOptionPane.ERROR_MESSAGE);
		}
	}
	
	public class FunnyJTextField extends JTextField {
		private static final long serialVersionUID = -8424757627429497332L;

		public FunnyJTextField(String text,int width) {
			super(text,width);
	
			addFocusListener(new FocusAdapter() {
			public void focusGained(FocusEvent fe) {
				selectAll();}});
		}
	}
	
	class ButtonListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			if (e.getActionCommand().equals("searchTF")) {
				System.out.println("Searching for Backgrounds...");
				gSearch = new ImageSearch(((JTextField)e.getSource()).getText()); 
				imgPanel();
			}
			if (e.getActionCommand().equals("restart")) {
				System.out.println("Not choosing an image");
				mainPanel();
			}
		}
	}
	
	public void saveImg(JLabel source) {
		thanksDialog(source);
		int i = Integer.parseInt(source.getName().substring(2));
		
		URL tmp = result.getImage(i).getURL();
		String[] tmpSplit = tmp.toString().split("\\.");
		String ext = tmpSplit[tmpSplit.length-1];
		
		//: get image index #, save into bg output folder
		try {
			FileUtils.copyURLToFile(tmp, new File(OUTPUT_BG_DIR + "\\" + saveIndex+"."+ext));
			System.out.println("Saved bg image #"+saveIndex);
			saveIndex++;
		} catch (IOException e) {
			JOptionPane.showMessageDialog(this, "Image Not Found!", "Error!", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
		}
		result = null;
	}
	
	class ImageListener implements MouseListener {
		public void mouseClicked(MouseEvent e) {
			chosenScene = (JLabel)e.getSource();
			System.out.println("You clicked on img: "+chosenScene.getName());
			saveImg(chosenScene);
		}
		public void mouseEntered(MouseEvent e) {}
		public void mouseExited(MouseEvent e) {}
		public void mousePressed(MouseEvent e) {}
		public void mouseReleased(MouseEvent e) {}
	}
	
	public static void main(String[] args) {
	      ScenePicker mainframe = new ScenePicker();
	      mainframe.setTitle("Compuprov Scene Picker!");
	      mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	      mainframe.setVisible(true);
	}
}
